from models.role import Role
from schemas.users import RolesResponse, RoleResponse, PermissionResponse


def set_role_response(role: Role) -> RoleResponse | None:
    if role:
        return RoleResponse(
            created_at=role.created_at,
            description=role.description,
            id=role.id,
            name=role.name,
            permissions= [PermissionResponse (
                name = permission.name,
                description = permission.description,
                father_id = permission.father_id,
                id = permission.id,
                created_at = permission.created_at
            ) for permission in role.permissions]
        )
    else:
        return None

class RoleRepository:
    def __init__(self, db):
        self.db = db

    def create_or_update_role(self, role: Role) -> Role:
        self.db.add(role)
        self.db.commit()
        self.db.refresh(role)
        return set_role_response(role)


    def delete_role(self, role_id:int):
        role = self.db.query(Role).filter_by(id=role_id).first()
        self.db.delete(role)
        self.db.commit()
        return role

    def filter_role(self, page:int|None, size:int|None) ->RolesResponse:
        roles = self.db.query(Role).offset((page - 1) * size).limit(size).all()
        total = self.db.query(Role).count()
        return RolesResponse(data=[set_role_response(role) for role in roles], paging={"page":page,"size":size,"total":total})

    def get_role_obj_by_id(self, role_id:int) -> Role:
        return self.db.query(Role).filter_by(id=role_id).first()

    def get_role_by_id(self, role_id:int) -> RoleResponse:
        role = self.db.query(Role).filter_by(id=role_id).first()
        return set_role_response(role)

    def get_role_by_name(self, name:str) -> Role:
        return self.db.query(Role).filter_by(name=name).first()
